package com.cn.learn.creator.util;

import lombok.extern.log4j.Log4j2;

import java.lang.reflect.Field;

/**
 * @ClassName ReflectUtil
 * @Description 反射工具类
 * @Author JiJiang
 * @Date 2023/7/13 16:59
 * @Version 1.0
 */
@Log4j2
public class ReflectUtil {


    public static <T extends Object> T getProperty(Object object, String propertyName, Class<T> valClz) {


        Class<?> clz = object.getClass();
        while (clz != null) {
            try {
                //获取字段对象
                Field declaredField = clz.getDeclaredField(propertyName);

                //暴力反射，不推荐
                declaredField.setAccessible(true);
                //直接获取属性
                return (T) declaredField.get(object);
            } catch (NoSuchFieldException e) {
//                e.printStackTrace();
                log.error("类：{}，无属性：{}", clz.getName(), propertyName);
                clz = clz.getSuperclass();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                break;
            }

        }


        return null;

    }

}
